package cn.itsource.interceptor;

import cn.itsource.domain.User;
import cn.itsource.util.UserContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LogInterceptor implements HandlerInterceptor {
    @Value("${client.log}")
    private String logPath;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("text/json;charset=utf-8");
        String type = request.getParameter("type");
        String token = StringUtils.isBlank(type) ? request.getHeader("token") : request.getParameter("token");
        if(StringUtils.isBlank(token)){
            if(StringUtils.isBlank(type)){
                response.getWriter().write("{\"success\":false,\"code\":401}");
            }else{
                response.sendRedirect(logPath);
            }
            return false;
        }
        User loginUser = UserContext.getLoginUser(token);
        if (loginUser == null) {
            if(StringUtils.isBlank(type)){
                response.getWriter().write("{\"success\":false,\"code\":401}");
            }else{
                response.sendRedirect(logPath);
            }
            return false;
        }
        return true;
    }
}
